import axios, { type AxiosResponse, type InternalAxiosRequestConfig, type Method } from 'axios'
import { showFailToast } from 'vant'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 网易严选线上接口封装
const wyyx = axios.create({
  baseURL: '/wyyx',
  timeout: 5000
})

// 尚品汇前台接口封装
const sph = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器的成功回调
const reqFulfilled = (config: InternalAxiosRequestConfig<any>) => {

  const token = window.localStorage.getItem('token')
  if (token) {
    config.headers.token = token
  }
  nprogress.start()
  if (config.baseURL === '/wyyx' && config.url?.startsWith('/xhr/search/searchAutoComplete')) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  }

  return config
}
// 请求拦截器的失败回调
const reqRejected = (error: any) => {
  nprogress.done()
  return Promise.reject(error)
}
// 响应拦截器的成功回调
const resFulfilled = (response: AxiosResponse<any, any>) => {
  nprogress.done()
  const data = response.data

  if (data.code !== '200' && data.code !== 200) {
    if (data.code === '208') {
      showFailToast('token,请重新登录')
      //退出登录并跳转
    } else {
      showFailToast(data.message)
    }
    return Promise.reject(data.message)
  } else {
    return data
  }
}
// 响应拦截器的失败回调
const resRejected = () => {
  nprogress.done()
  showFailToast('网络异常')
  return new Promise(() => {})
}

// 添加请求拦截器
wyyx.interceptors.request.use(reqFulfilled, reqRejected)
sph.interceptors.request.use(reqFulfilled, reqRejected)

// 添加响应拦截器
wyyx.interceptors.response.use(resFulfilled, resRejected)
sph.interceptors.response.use(resFulfilled, resRejected)

interface IResWyyx<T = any> {
  data: T
  code: string
}

// 最终使用的网易严选http方法
const wyyxHttp = <T>(url: string, method: Method, data?: any): Promise<IResWyyx<T>> => {
  const newMethod = method.toUpperCase()
  return wyyx.request({
    url,
    method: newMethod,
    data: newMethod === 'POST' || newMethod === 'PUT' || newMethod === 'DELETE' ? data : {},
    params: newMethod === 'GET' ? data : {}
  })
}

interface IResponseData<T> {
  code: number
  message: string
  ok: boolean
  data: T
}

// 最终使用的尚品汇http方法
const sphHttp = <T>(url: string, method: Method, data?: any): Promise<IResponseData<T>> => {
  const newMethod = method.toUpperCase()
  return sph.request({
    url,
    method: newMethod,
    data: newMethod === 'POST' || newMethod === 'PUT' || newMethod === 'DELETE' ? data : {},
    params: newMethod === 'GET' ? data : {}
  })
}

export { wyyx, wyyxHttp, sphHttp }
